<template>
  <div class="w-full">
    <div class="box p-1 mt-3 block sm:hidden">
      <van-cell is-link :title="selText" @click="showActionSheet = true"/>
      <van-action-sheet v-model:show="showActionSheet" :actions="actions" @select="onSelect"/>
    </div>
    <div
        class="hidden sm:grid 2xl:grid xl:grid lg:grid md:grid grid-cols-1 2xl:grid-cols-5 xl:grid-cols-5 lg:grid-cols-5 gap-3 mt-3">
      <div class="col-span-1 sm:col-span-1 2xl:col-span-2 xl:col-span-2 lg:col-span-2 p-3 box intro-y">
        <!--        <chinaMap @selProvince="changeProvince" @getMapData="getMapData" :provinceAdcode="provinceAdcode"/>-->
        <chartMap :provinceAdcode="provinceAdcode" @selProvince="changeProvince" @selProvinceName="selProvinceName"/>
      </div>
      <div class="col-span-1 sm:col-span-1 2xl:col-span-3 xl:col-span-3 lg:col-span-3 p-3 box intro-y">
        <div class="flex justify-between items-center border-b border-slate-200/60 dark:border-darkmode-400 pb-5 mb-5">
          <div class="font-medium text-base truncate">选择省份</div>
          <div class="relative">
            <el-input v-model="searchQuery" style="width: 240px" @input="handleInput" placeholder="搜索"
                      :prefix-icon="Search"/>
            <div class="absolute bg-white border w-full z-50" v-if="searchResult.length > 0">
              <div class="s-result p-2 cursor-pointer" v-for="(item, index) in searchResult"
                   @click="searchProvince(item)">
                {{ item.regionName }}
              </div>
            </div>
          </div>
        </div>
        <province @changeProvince="changeProvince" :selectArea="selectArea" :dataSource="dataSource"/>
      </div>
    </div>
    <div
        class="sm:grid 2xl:grid xl:grid lg:grid md:grid grid-cols-1 2xl:grid-cols-5 xl:grid-cols-5 lg:grid-cols-5 gap-3 mt-3">
      <div class="col-span-1 sm:col-span-1 2xl:col-span-2 xl:col-span-2 lg:col-span-2 p-3 box intro-y">
        <!--        <threeDMap :adcode="adcode" :mapData="mapData" @changeCity="changeCity"/>-->
        <chartAreaMap :provinceAdcode="provinceAdcode"/>
      </div>
      <div class="col-span-1 sm:col-span-1 2xl:col-span-3 xl:col-span-3 lg:col-span-3 p-3 box intro-y">
        <wTable :tableData="tableData"/>
      </div>
    </div>
    <div class="box mt-5 border-t intro-y">
      <div class="title text-center p-3">新能源初装对比</div>
      <div class="report-chart">
        <chart :tableData="tableData"/>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, computed, onMounted} from "vue";
import threeDMap from "./threeDMap.vue";
import wTable from "./wTable.vue";
import province from "./province.vue";
import chinaMap from "./chinaMap.vue";
import chartMap from "./chartMap.vue"
import chartAreaMap from "./chartAreaMap.vue"
import {debounce} from 'lodash'
import chart from "./chart.vue"
import {Search} from "@element-plus/icons-vue";
import * as $api from "@/api/api";

const provinceAdcode = ref(Number(localStorage.getItem("regionCode")));
const selText = ref("选择省份")
const showActionSheet = ref(false);
const dataSource = ref(null);
const tableData = ref([]);
const actions = ref([]);
const onSelect = (item) => {
  mapData.value = convertDataAtoB(item);
  queryCityByRegion(item.regionCode);
  console.log(mapData.value);
  selText.value = item.name;
  // 默认情况下点击选项时不会自动收起
  // 可以通过 close-on-click-action 属性开启自动收起
  showActionSheet.value = false;
};
const params = ref({
  today: new Date(),
  tomorrow: new Date(),
  afterTomorrow: new Date(),
  dayAfterTomorrow: new Date(),
});

//搜索框结果
const searchQuery = ref("");
// 通过城市名筛选的列表
const searchResult = ref([]);
// 传到子地图的城市名
const selectArea = ref("");
const userKey = ref(localStorage.getItem("userKey"));
const adcode = ref("");
const mapData = ref(null);
const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始，所以需要+1，并且保证两位数
  const day = String(date.getDate()).padStart(2, "0"); // 保证日期是两位数
  return `${year}-${month}-${day}`;
};
const dates = computed(() => ({
  today: formatDate(params.value.today),
  tomorrow: formatDate(params.value.tomorrow),
  afterTomorrow: formatDate(params.value.afterTomorrow),
  dayAfterTomorrow: formatDate(params.value.dayAfterTomorrow),
}));
params.value.tomorrow.setDate(params.value.today.getDate() + 1);
params.value.afterTomorrow.setDate(params.value.tomorrow.getDate() + 1);
params.value.dayAfterTomorrow.setDate(params.value.afterTomorrow.getDate() + 1);

onMounted(() => {
  getRegionList();
});

// 获取省列表
const getRegionList = () => {
  $api.GetRegionList().then(res => {
    dataSource.value = res;
    actions.value = res.map(item => ({
      lat: item.lat,
      lon: item.lon,
      name: item.regionName,
      regionCode: item.regionCode,
    }));
    // 筛选出与登录返回省份相同的省份信息
    const filterData = res.filter(item => Number(item.regionCode) === provinceAdcode.value);
    mapData.value = convertDataAtoB(filterData[0]);
    queryCityByRegion(filterData[0].regionCode);
  })
}
// 根据省查询城市
const queryCityByRegion = (code) => {
  $api.QueryCityByRegion({
    unitKey: "",
    userKey: userKey.value,
    key: code
  }).then(res => {
    console.log(res);
    tableData.value = res;
  })
}
// 切换城市
const changeCity = (item) => {
  getWeatherData(item);
};
// 获取市一周数据
const getWeatherData = (code) => {
  $api.QueryByCity({
    unitKey: "",
    userKey: userKey.value,
    num: 7,
    code: code
  }).then(res => {
    console.log(res);
    tableData.value = res;
  })
}
// 监听输入事件
const handleInput = () => {
  searchDebounced(searchQuery.value)
}
// 防抖后的搜索函数
const searchDebounced = debounce((query) => {
  if (!query) {
    searchResult.value = []
  } else {
    // 从dataSource中搜索符合query的数据
    searchResult.value = dataSource.value.filter((item) => item.regionName.toLowerCase().includes(query.toLowerCase()));
    // searchResult.value = ["北京市", "上海市"]
  }
}, 500) // 防抖延迟500ms

const convertDataAtoB = (data) => {
  return {
    acroutes: [parseInt(100000)], // 假设acroutes是一个数组，元素为regionCode的整数值
    adcode: parseInt(data.regionCode), // 直接使用regionCode作为adcode
    center: [data.lon, data.lat], // 经度在前，纬度在后
    centroid: [data.lon, data.lat], // 同center
    childrenNum: null, // 数据A中没有提供，这里设置为null
    level: "province", // 根据regionName推断
    name: data.regionName || data.name, // 使用regionName
    parent: {adcode: 100000}, // 假设这是国家代码
    subFeatureIndex: null // 数据A中没有提供，这里设置为null
  };
}
// 点击搜索结果
const searchProvince = (item) => {
  console.log(item);
  queryCityByRegion(item.regionCode);
  searchQuery.value = item.regionName;
  selectArea.value = item.regionName;
  searchResult.value = [];
  mapData.value = convertDataAtoB(item);
  provinceAdcode.value = item.regionCode;
}
const selProvinceName = (item) => {
  selectArea.value = item;
}
const changeProvince = (item) => {
  provinceAdcode.value = item.regionCode ? item.regionCode : item;
  queryCityByRegion(item.regionCode ? item.regionCode : item);
  mapData.value = convertDataAtoB(item);
};
const getMapData = (e) => {
  mapData.value = e;
  // queryCityByRegion(e.adcode);
}
</script>

<style lang="scss" scoped>
.title {
  font-size: 20px;
  color: #555555;
  font-weight: bold;
}
</style>